package org.grow.studentscore.controller;

import org.grow.common.entity.ExchangeScoreDto;
import org.grow.studentscore.dao.StudentScoreDao;

import org.grow.studentscore.entity.StudentScore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.time.LocalDateTime;

/**
 * @Author: xwg
 * @CreateDate: 21-8-12
 */

@RestController
@RequestMapping("/ssc")
public class StudentScoreController {

    @Autowired
    private StudentScoreDao studentScoreDao;

    @GetMapping("/time")
    public LocalDateTime showTime(){
        return LocalDateTime.now();
    }
    @PutMapping("/exchangeScore")
    public String exchangeScore(@RequestBody ExchangeScoreDto exchangeScoreDto) {

        Integer dealScore = exchangeScoreDto.getDealScore();
        if(dealScore<0) throw new RuntimeException("交易分数不能小于0");
        String consumerName = exchangeScoreDto.getConsumerName();
        String supplierName = exchangeScoreDto.getSupplierName();
        StudentScore consumer = studentScoreDao.findByName(consumerName);
        StudentScore supplier = studentScoreDao.findByName(supplierName);
        supplier.setOnlineScore(supplier.getOnlineScore() - dealScore);
        studentScoreDao.save(supplier);

        consumer.setOnlineScore(consumer.getOnlineScore() + dealScore);
        studentScoreDao.save(consumer);
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String token = requestAttributes.getRequest().getHeader("Cookie");
        System.out.println("cookie : "+token);
        return "good";

    }
}
